<template>
  <div class="app-container">
    <!-- 积分信息显示 -->
    <div class="points-info">
      <span class="points-label">我的积分：</span>
      <span class="points-value">{{ userPoints }}</span>
    </div>

    <!-- 商品列表 -->
    <div class="goods-container">
      <el-row :gutter="20">
        <el-col
          v-for="item in goodsList"
          :key="item.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card class="goods-card" shadow="hover">
            <div class="goods-image">
              <img :src="getImageUrl(item.image) || defaultImage" :alt="item.name">
            </div>
            <div class="goods-info">
              <h3 class="goods-name">{{ item.name }}</h3>
              <p class="goods-description">{{ item.description }}</p>
              <div class="goods-footer">
                <div class="goods-points">
                  <i class="el-icon-coin" />
                  <span>{{ item.points }}积分</span>
                </div>
                <div class="goods-stock">库存：{{ item.stock }}</div>
                <el-button
                  type="primary"
                  size="small"
                  :disabled="item.stock <= 0 || userPoints < item.points"
                  @click="handleExchange(item)"
                >
                  {{ getExchangeButtonText(item) }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageIndex"
      :limit.sync="queryParams.pageSize"
      @pagination="getGoodsList"
    />

    <!-- 兑换确认对话框 -->
    <el-dialog
      title="确认兑换"
      :visible.sync="exchangeDialogVisible"
      width="400px"
      center
    >
      <div class="exchange-confirm">
        <div class="goods-preview">
          <img :src="getImageUrl(selectedGoods.image) || defaultImage" :alt="selectedGoods.name">
          <div class="goods-details">
            <h4>{{ selectedGoods.name }}</h4>
            <p>{{ selectedGoods.description }}</p>
            <div class="points-cost">
              <i class="el-icon-coin" />
              <span>需要 {{ selectedGoods.points }} 积分</span>
            </div>
          </div>
        </div>
        <div class="confirm-text">
          确定要兑换这个商品吗？兑换后将扣除 {{ selectedGoods.points }} 积分。
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exchangeDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="exchangeLoading" @click="confirmExchange">
          确认兑换
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getExchangeGoods, exchangeGoods, getCurrentUserPoints } from '@/api/points'
import Pagination from '@/components/Pagination'

export default {
  name: 'PointsExchange',
  components: {
    Pagination
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      goodsList: [],
      total: 0,
      userPoints: 0,
      queryParams: {
        pageIndex: 1,
        pageSize: 10000
      },
      exchangeDialogVisible: false,
      selectedGoods: {},
      exchangeLoading: false,
      defaultImage: 'https://via.placeholder.com/200x150?text=商品图片'
    }
  },
  created() {
    this.getUserPoints()
    this.getGoodsList()
  },
  methods: {
    // 判断是否禁用兑换按钮
    isExchangeDisabled(item) {
      return item.stock <= 0 || this.userPoints < item.points
    },
    // 获取按钮显示文本
    getExchangeButtonText(item) {
      if (item.stock <= 0) return '缺货'
      if (this.userPoints < item.points) return '积分不足'
      return '立即兑换'
    },
    // 获取用户积分
    async getUserPoints() {
      try {
        const response = await getCurrentUserPoints()
        this.userPoints = response.data.total_points || 0
      } catch (error) {
        console.error('获取用户积分失败:', error)
        this.userPoints = 0
      }
    },
    // 获取商品列表
    async getGoodsList() {
      try {
        const response = await getExchangeGoods(this.queryParams)
        this.goodsList = response.data.data || []
        this.total = response.data.totalCount || 0
      } catch (error) {
        this.$message.error('获取商品列表失败')
        console.error('获取商品列表失败:', error)
      }
    },
    // 处理兑换
    handleExchange(goods) {
      if (goods.stock <= 0) {
        this.$message.warning('商品库存不足')
        return
      }
      if (this.userPoints < goods.points) {
        this.$message.warning('积分不足，无法兑换')
        return
      }
      this.selectedGoods = goods
      this.exchangeDialogVisible = true
    },
    // 确认兑换
    async confirmExchange() {
      this.exchangeLoading = true
      try {
        await exchangeGoods({ goods_id: this.selectedGoods.id })
        this.$message.success('兑换成功！')
        this.exchangeDialogVisible = false
        // 刷新数据
        this.getUserPoints()
        this.getGoodsList()
      } catch (error) {
        this.$message.error(error.message || '兑换失败')
      } finally {
        this.exchangeLoading = false
      }
    },
    // 获取图片完整URL
    getImageUrl(imagePath) {
      if (!imagePath) return ''
      if (imagePath.indexOf('http') !== -1) {
        return imagePath
      } else {
        return this.baseURL + '/' + imagePath
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.points-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  align-items: center;

  .points-label {
    font-size: 16px;
    color: #606266;
    margin-right: 10px;
  }

  .points-value {
    font-size: 24px;
    font-weight: bold;
    color: #409EFF;
  }
}

.goods-container {
  margin-bottom: 20px;
}

.goods-card {
  margin-bottom: 20px;
  transition: transform 0.2s;

  &:hover {
    transform: translateY(-2px);
  }
}

.goods-image {
  width: 100%;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 10px;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.goods-info {
  .goods-name {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin: 0 0 8px 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .goods-description {
    font-size: 12px;
    color: #909399;
    margin: 0 0 10px 0;
    height: 36px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

.goods-footer {
  .goods-points {
    display: flex;
    align-items: center;
    color: #E6A23C;
    font-weight: bold;
    margin-bottom: 5px;

    i {
      margin-right: 4px;
    }
  }

  .goods-stock {
    font-size: 12px;
    color: #909399;
    margin-bottom: 10px;
  }
}

.exchange-confirm {
  .goods-preview {
    display: flex;
    margin-bottom: 20px;

    img {
      width: 80px;
      height: 60px;
      object-fit: cover;
      border-radius: 4px;
      margin-right: 15px;
    }

    .goods-details {
      flex: 1;

      h4 {
        margin: 0 0 5px 0;
        color: #303133;
      }

      p {
        margin: 0 0 8px 0;
        font-size: 12px;
        color: #909399;
      }

      .points-cost {
        display: flex;
        align-items: center;
        color: #E6A23C;
        font-weight: bold;

        i {
          margin-right: 4px;
        }
      }
    }
  }

  .confirm-text {
    text-align: center;
    color: #606266;
    line-height: 1.5;
  }
}
</style>
